package com.coai.file.controller

import com.coai.common.dto.ApiResponse
import com.coai.file.dto.*
import com.coai.file.model.FileCategory
import com.coai.file.service.FileService
import kotlinx.coroutines.runBlocking
import org.springframework.core.io.InputStreamResource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.InputStream

@RestController
@RequestMapping("/api/files")
class FileController(
    private val fileService: FileService
) {
    
    /**
     * 上传文件
     */
    @PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun uploadFile(
        @RequestParam("file") file: MultipartFile,
        @RequestParam(required = false) conversationId: String?,
        @RequestParam(required = false) messageId: String?,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<FileUploadResponse> = runBlocking {
        val result = fileService.uploadFile(file, userId, conversationId, messageId)
        ApiResponse.success(result, "文件上传成功")
    }
    
    /**
     * 初始化分片上传
     */
    @PostMapping("/chunk/init")
    fun initChunkUpload(
        @RequestBody request: InitChunkUploadRequest,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<InitChunkUploadResponse> = runBlocking {
        val result = fileService.initChunkUpload(request, userId)
        ApiResponse.success(result)
    }
    
    /**
     * 上传分片
     */
    @PostMapping("/chunk/upload")
    fun uploadChunk(
        @RequestParam uploadId: String,
        @RequestParam chunkIndex: Int,
        @RequestParam("chunk") chunk: MultipartFile,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<ChunkUploadStatusResponse> = runBlocking {
        val result = fileService.uploadChunk(
            uploadId, chunkIndex, chunk.inputStream, chunk.size
        )
        ApiResponse.success(result)
    }
    
    /**
     * 完成分片上传
     */
    @PostMapping("/chunk/complete")
    fun completeChunkUpload(
        @RequestParam uploadId: String,
        @RequestParam(required = false) conversationId: String?,
        @RequestParam(required = false) messageId: String?,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<FileUploadResponse> = runBlocking {
        val result = fileService.completeChunkUpload(uploadId, conversationId, messageId)
        ApiResponse.success(result, "文件上传完成")
    }
    
    /**
     * 下载文件
     */
    @GetMapping("/{fileId}/download")
    fun downloadFile(
        @PathVariable fileId: String,
        @AuthenticationPrincipal userId: String
    ): ResponseEntity<InputStreamResource> = runBlocking {
        val (stream, file) = fileService.downloadFile(fileId, userId)
        
        ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(file.mimeType))
            .header(HttpHeaders.CONTENT_DISPOSITION, 
                "attachment; filename=\"${file.originalName}\"")
            .body(InputStreamResource(stream))
    }
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{fileId}")
    fun deleteFile(
        @PathVariable fileId: String,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<Unit> = runBlocking {
        fileService.deleteFile(fileId, userId)
        ApiResponse.success(message = "文件已删除")
    }
    
    /**
     * 获取用户文件列表
     */
    @GetMapping("/my-files")
    fun getMyFiles(
        @RequestParam(required = false) category: FileCategory?,
        @RequestParam(defaultValue = "0") page: Int,
        @RequestParam(defaultValue = "20") size: Int,
        @AuthenticationPrincipal userId: String
    ): ApiResponse<FileListResponse> {
        val result = fileService.getUserFiles(userId, category, page, size)
        return ApiResponse.success(result)
    }
    
    /**
     * 获取存储使用统计
     */
    @GetMapping("/storage-usage")
    fun getStorageUsage(
        @AuthenticationPrincipal userId: String
    ): ApiResponse<StorageUsageDto> {
        val usage = fileService.getStorageUsage(userId)
        return ApiResponse.success(usage)
    }
}
